package com.easy.service.impl;

import com.easy.annotation.LogMethod;
import com.easy.bean.Doctor;
import com.easy.mapper.DoctorMapper;
import com.easy.service.DoctorService;
import com.easy.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DoctorServiceImpl implements DoctorService {
    //使用 Spring 的 @Autowired 注解
    //自动注入 DoctorMapper 数据访问对象，用于与数据库交互。
    @Autowired
    DoctorMapper doctorMapper;

    @Override
    public Object page(Page page, Doctor doctor) {
        // 查询总条数
        int count = doctorMapper.count(doctor);
        page.setCount(count);
        // 查询分页数据
        List<Doctor> list = doctorMapper.page(doctor,page);
        page.setData(list);
        return page;
    }


    @Override
    public Map<String, Object> pageWithDepartment(Doctor doctor, int current, int limit) {
        Map<String, Object> page = new HashMap<>();
        page.put("start", (current - 1) * limit);
        page.put("limit", limit);

        Map<String, Object> result = new HashMap<>();
        result.put("data", doctorMapper.pageWithDepartment(doctor, page));
        result.put("count", doctorMapper.countWithDepartment(doctor));
        return result;
    }

    @Override
    @Cacheable(value = "doctor",key = "#p0")//#p0 表示参数
    @LogMethod(serviceName = "新增医生信息")
    public Doctor add(Doctor doctor) {
        //新增数据
        doctorMapper.add(doctor);
        //通过主键查询数据库中的数据
        Doctor result = doctorMapper.one(doctor.getId());
        return result;
    }

    //删除缓存中对应的数据        加上allEntries = true之后是清空所有的实例
    @CacheEvict(value = "doctor",key = "#id")
    @Override
    @LogMethod(serviceName = "删除医生信息")
    public int del(Integer id) {
        return doctorMapper.del(id);
    }


    //对缓存中的数据进行更新   在修改完数据后  将修改后的数据进行查询缓存
    @CachePut(value = "doctor",key = "#p0.id")
    @Override
    @LogMethod(serviceName = "修改医生信息")
    public Doctor edit(Doctor doctor) {
        System.out.println(doctor);
        doctorMapper.edit(doctor);
        //通过主键修改数据库中的数据
        Doctor result = doctorMapper.one(doctor.getId());
        return result;
    }

    @Override
    @LogMethod(serviceName = "查询医生信息")
    public List<Doctor> all(Doctor doctor) {
        return doctorMapper.all(doctor);
    }

    //查询使用缓存 value记录查询的内容 key记录其标识
    // #来调用参数  用pn来获取第n个参数（#p1调用第一参数）
    @Cacheable(value = "doctor",key = "#p0")
    @Override
    @LogMethod(serviceName = "查询医生信息")
    public Doctor one(Integer id) {
        return doctorMapper.one(id);
    }
}


















